package com.admin.core;

import com.admin.business.background.entityClasses.VenusArticle;
import com.admin.business.background.venusArticle.VenusArticleDao;
import com.admin.business.background.venusOaApprovalRecord.VenusOaApprovalRecordDao;
import com.admin.business.background.venusOaDiscoloration.VenusOaDiscolorationDao;
import com.admin.business.background.venusProjectCostsSet.VenusProjectCostsSetDao;
import com.admin.business.background.venusSysActivity.VenusSysActivityDao;
import com.admin.business.background.venusSysUserFranchise.VenusSysUserFranchiseDao;
import com.admin.business.voteEssentialInformation.VoteEssentialInformationService;
import com.admin.utils.Journalism;
import com.admin.utils.MobileSendUtil;
import com.admin.utils.RandomStrUtil;
import com.tiangong.framework.bo.CDO;
import com.zmbsms.os.core.util.ObjectUtils;
import com.zmbsms.os.core.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 定时器
 */
@Configuration
@Slf4j
@EnableScheduling
@Service("timer")
public class Timer {


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Resource
    VoteEssentialInformationService voteEssentialInformationService;
    //新闻表
    @Resource
    VenusArticleDao venusArticleDao;

    @Resource
    VenusSysActivityDao venusSysActivityDao;
    //   物业费
    @Resource
    VenusProjectCostsSetDao venusProjectCostsSetDao;
    @Resource
    VenusSysUserFranchiseDao venusSysUserFranchiseDao;
    //请假申请表信息
    @Resource
    VenusOaApprovalRecordDao venusOaApprovalRecordDao;
    //app app致灰
    @Resource
    VenusOaDiscolorationDao venusOaDiscolorationDao;
    /**
     * 每天凌晨1点，查询修改委员报名公示状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void membersVoteStateUpdate() throws ParseException {
        voteEssentialInformationService.updateMembersVoteStateByTimer(null);
    }

    /**
     * 每天凌晨1点，查询修改首次业主大会公示状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void firstOwnersMeetingVoteStateUpdate() throws ParseException {
        voteEssentialInformationService.firstOwnersMeetingVoteState(null);
    }


    /**
     * 每天凌晨1点，查询修改筹备组招募状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void preparatoryGroupApplicationStateUpdate() throws ParseException {
        voteEssentialInformationService.updatePreparatoryGroupApplicationStateByTimer(null);
    }

    /**
     * 每天凌晨1点，查询修改筹备组投票状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void preparatoryGroupVoteStateUpdate() throws ParseException {
        voteEssentialInformationService.updatePreparatoryGroupVoteStateByTimer(null);
    }


    /**
     * idatakey值
     */
     private String APIKEY = "WUyGOKocCeadfr85NXnvwcmMjDvghksuP9wKB14wo7hZzko3SMP218ijrfihC2x3";

    private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());

    /**
     * idataurl
     *
     * @url www.idata.cn
     */
    private String URL = "http://api01.idataapi.cn:8000/article/idataapi?" +
            "apikey=" + APIKEY +
            "&kw=物业服务纠纷,物业管理纠纷,业主大会,业主委员会,业委会,物业管理纠纷,业主矛盾,房屋买卖纠纷" +
            "&kwMode=or" +
            "&KwPosition=3" +
            "&fields=id,url,title,content,html,imageUrls,publishDate,posterScreenName,viewCount,appName";

    /**
     * 定时同步新闻
     * 每天8点-16点每2个小时执行一次
     *
     * @throws IOException
     * @date 2020年10月10日13点43分
     * @name wdf
     */
    @Scheduled(cron = "0 0 8-16/2 * * *")
    public void timingQuickOrder() throws IOException, JSONException {
        Journalism journalism = new Journalism();
        JSONObject journalismJson = journalism.getRequestFromUrl(URL);
        if (journalismJson.getInt("retcode")!=100702){//先不等于100702
            journalism(journalismJson);
        }

        logger.info("新闻更新成功!!! 时间为" + new Date());
    }


    /**
     * 新闻存储处理
     *
     * @param journalismJson
     * @date 2020年10月10日11点43分
     * @name wdf
     */
    public void journalism(JSONObject journalismJson) {
        try {
            JSONArray datas = journalismJson.getJSONArray("data");
            //获取data处理新闻
            for (int i = 0; i < datas.length(); i++) {
                JSONObject data = datas.getJSONObject(i);
                if (ObjectUtils.isNull(data)){
                    continue;
                }
                String title = data.getString("title");
                String id = data.getString("id");
                String content = data.getString("content");
                VenusArticle venusArticle = new VenusArticle();
                //校验新闻json中是否存在imageUrls的key
                if (data.has("imageUrls")) {
                    JSONArray imageUrls = data.getJSONArray("imageUrls");
                    System.out.println(imageUrls);
                    venusArticle.setImage(imageUrls.getString(0));
                }
                if (data.has("posterScreenName")) {
                    String posterScreenName = data.getString("posterScreenName");
                    venusArticle.setAuthor(posterScreenName);
                }
                if (data.has("source")) {
                    String source = data.getString("source");
                    venusArticle.setSource(source);
                }
                if (data.has("viewCount")) {
                    int viewCount = data.getInt("viewCount");
                    venusArticle.setViewNum(viewCount);
                }
                if (data.has("html")) {
                    String html = data.getString("html");
                    venusArticle.setContent(html);
                } else {
                    if (data.has("content"))
                        venusArticle.setContent(content);
                }
                venusArticle.setIdataId(id);
                venusArticle.setMainHeading(title);
                venusArticle.setSubParentId(9l);
                venusArticle.setCreateTime(new Date());
                venusArticle.setSysUserId(256l);
                venusArticle.setSubId(10l);
                venusArticle.setCreateTime(new Date());


                if (venusArticleDao.articleCount(id) > 0) {
                    logger.info("新闻重复不进行数据存储!!! id为：" + id);
                } else {
                    String mainHeading = title.trim().substring(0, 5);
                    int mainHeadingCount = venusArticleDao.getVenusMainHeadingCount(mainHeading);
                    if (mainHeadingCount > 0) {
                        logger.info("新闻重复不进行数据存储!!! 标题为：" + mainHeading);
                    } else {
                        String[] src = {"小区", "物业", "停车", "车位", "业主", "酬金制", "楼道", "消防通道", "人防", "业委会",
                                "房产", "房地产", "公共收益", "储藏室", "水", "电", "气", "暖", "燃气", "管家", "自治", "自管", "高空抛物", "垃圾", "门禁",
                                "监控", "道闸", "消防", "保洁", "保安", "维修", "绿化", "工程", "扯管", "选聘", "解聘", "公共维修资金", "恭维",
                                "协会", "法律", "民法典", "房屋", "偷盗", "装修", "公开", "阳台", "居民", "环境", "没收房", "房", "居住"};
                        for (int j = 0; j < src.length; j++) {
                            if (title.contains(src[i])) {
                                venusArticleDao.addArticleJournalism(venusArticle);
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //每天1：05执行（0 05 03 ? * *） (0 */1 * * * ?)一分钟一次
    @Scheduled(cron = "0 05 01 ? * *")
    public void testTasks() {
        // 定时处理周期物业费和附加费
        try {
            // 找到所有设置物业费的房间
            List<CDO> setList = venusProjectCostsSetDao.getCostsSetList();
            if (ObjectUtils.isNotNull(setList)) {
                Map<String, CDO> map = new HashMap<>();
                for (CDO list : setList) {// 每个物业费设置
                    String idArray[] = null;
                    if (list.getInteger("costs_scope_type").equals("1")) {
                        idArray = list.getString("costs_scope_value").split("#")[1].split(",");
                    } else {
                        idArray = list.getString("costs_scope_value").split(",");
                    }
                    List<CDO> childList = venusProjectCostsSetDao.getChildByPId(list.getString("id"));
                    list.set("childSetList", childList);
                    if (ObjectUtils.isNotNull(idArray)) {// 每个物业费设置的附加费
                        for (int i = 0; i < idArray.length; i++) {
                            map.put(idArray[i], list);
                        }
                    }
                }

                if (ObjectUtils.isNotNull(map)) {
                    // 当前时间
                    Date now = new Date();
                    SimpleDateFormat dp = new SimpleDateFormat("yyyy-MM-dd");
                    CDO roomMap=new CDO();
                    roomMap.set("map",map);

                    List<CDO> roomList = venusProjectCostsSetDao.getRoomListByMap(roomMap);
                    for (CDO room : roomList) {
                        System.out.println(room.get("startTime") + "***" + room.get("endTime"));
                        // 如果最后一个缴费周期的时间比当前时间小就推出下一次缴费周期
                        if (ObjectUtils.isNotNull(room.get("endTime")) && dp.parse(room.get("endTime").toString()).getTime() < now.getTime()) {
                            // 开始推物业费周期
                            CDO set = map.get(room.get("roomId").toString());
                            Date p = dp.parse(room.get("endTime").toString());
                            CDO period = new CDO();
                            period.set("roomId", room.get("roomId"));
                            period.set("startTime", p);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(p);
                            int num = 0;// 月数
                            if (set.get("costsPeriodUnit").equals(4)) {// 月
                                calendar.add(Calendar.MONTH, +1);// 缴费时间后一个月
                                num = 1;
                            } else if (set.get("costsPeriodUnit").equals(3)) {// 季度
                                calendar.add(Calendar.MONTH, +3);// 缴费时间后3个月
                                num = 3;
                            } else if (set.get("costsPeriodUnit").equals(2)) {// 半年
                                calendar.add(Calendar.MONTH, +6);// 缴费时间后半年
                                num = 6;
                            } else if (set.get("costsPeriodUnit").equals(1)) {// 年
                                calendar.add(Calendar.YEAR, +1);// 缴费时间后一年
                                num = 12;
                            }
                            period.set("endTime", dp.format(calendar.getTime()));
                            period.set("sign", 1);
                            period.set("createTime", new Date());
                            // 计算这周期物业费开始
                            Double value = Double.valueOf(room.get("roomAreaOfStructure").toString()) * Double.valueOf(set.get("costsPrice").toString()) * num;
                            period.set("periodShouldMoney", value);
                            List<CDO> periodListResult = new ArrayList<>();
                            periodListResult.add(period);
                            //---------------------------------------
                            // 开始推附加费周期
                            if (ObjectUtils.isNotNull(periodListResult)) {
                                CDO addProCost=new CDO();
                                addProCost.set("periodListResult",periodListResult);
                                venusProjectCostsSetDao.addProjectCostPeriodChild(addProCost);
                                // 推出本期的附加费周期
                                // =================================分割线=====================================
                                List<CDO> allChildList = map.get(room.getString("roomId")).getCDOList("childSetList");

                                // 推理附加费周期开始
                                if (!allChildList.isEmpty()) {
                                    for (CDO periodNext : periodListResult) {
                                        for (CDO itemNext : allChildList) {
                                            CDO v_p_c_a_c = new CDO();
                                            v_p_c_a_c.set("additionalChargeCostPeriodId", periodNext.get("id"));
                                            v_p_c_a_c.set("costSetChildId", itemNext.get("costsSetChildId"));
                                            v_p_c_a_c.set("additionalChargeBeginTime", dp.format(periodNext.get("startTime")));
                                            v_p_c_a_c.set("additionalChargeEndTime", periodNext.get("endTime"));
                                            v_p_c_a_c.set("createTime", new Date());
                                            v_p_c_a_c.set("additionalChargeSign", 1);
                                            v_p_c_a_c.set("roomId", periodNext.get("roomId"));
                                            if (!v_p_c_a_c.isEmpty()){
                                                venusProjectCostsSetDao.addResultList(v_p_c_a_c);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    System.out.println(roomList);
                }
            }
            System.out.println("定时任务执行时间：" + dateFormat.format(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    //每天2：05执行（0 05 03 ? * *） (0 */1 * * * ?)一分钟一次
    @Scheduled(cron = "0 05 02 ? * *")
    public void freeOrderTme(){
        try {
            //查询未支付的订单执行删除
            venusProjectCostsSetDao.deleteOrder();
        }catch (Exception e){
            e.printStackTrace();
        }
    }



//    短信没写


    /**
     * 软件加盟定时每晚修改未交费的订单
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    public void softwareJoining(){
        //查询未缴费软件订单修改订单号信息
        List<CDO> venusUnpaidFranchise = venusSysUserFranchiseDao.getVenusUnpaidFranchise();
        for (CDO cdo : venusUnpaidFranchise) {
            String id = cdo.getString("id");
            Date currTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String time = formatter.format(currTime);
            String timeMillis = currTime.getTime() + "";
            String item = timeMillis.substring(timeMillis.length() - 4);//时间戳后四位
            String codeItem = RandomStrUtil.getRandInt(4);//随机码四位
            String code = "DL" + time + item + codeItem;//编号
            if (StringUtils.isEmpty(id)){
                continue;
            }
            String invitationCode = cdo.getString("invitationCode");
            if (StringUtils.isEmpty(invitationCode)){
                continue;
            }
            CDO update=new CDO();
            update.set("id",code);
            update.set("invitationCode",invitationCode);
            venusSysUserFranchiseDao.updatePortalUserFranchiseMapper(update);
        }
    }



    /**
     * @Author Zwl
     * @Description //TODO  月初自动拒绝上月的请假申请
     * @Date 2022-11-21 15:11:17
     * @Param
     * @return
     */
    @Scheduled(cron="0 0 0 1 * ?")//每月一号执行一次
    public void leaveApproval(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        CDO cdo1 = new CDO();

        CDO appRescord=new CDO();
        appRescord.set("approval_type",0);
        List<CDO> mapperList = venusOaApprovalRecordDao.getVenusOaApprovalRecordListPage(appRescord);//0.请假 1.补卡
        for (CDO cdo : mapperList) {
            String leave_time = cdo.getString("leave_time");//
            Date parse = null;
            try {
                parse = sdf.parse(leave_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (parse.before(date)&&!parse.equals(date)){//判断请假的结束时间是都小于当前时间
                cdo1.set("id",cdo.getLong("id"));
                cdo1.set("approval_state",2);
                cdo1.set("update_time",new Date());
                venusOaApprovalRecordDao.updateVenusOaApprovalRecordById(cdo1);

                //修改审批表信息
                CDO after = new CDO();//审批表
                after.set("pid",cdo.getLong("id"));
                after.set("approval_state",2);
                after.set("approval_time",new Date());
                after.set("approval_opinion","已超过请假结束时间月份,系统自动拒绝");
                after.set("not_approved","0");
                venusOaApprovalRecordDao.updateVenusOaLeaveApproval(after);
            }
        }
    }

    /**
     * @Author Zwl
     * @Description //TODO 过了五号,自动拒绝上一个月的补卡申请
     * @Date 2022-11-3 13:36:32
     * @Param
     * @return
     */
    @Scheduled(cron="0 0 0 5 * ?")//每月五号执行一次
    public void automaticApproval(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M");
        CDO appRescord=new CDO();
        appRescord.set("approval_type",1);
        List<CDO> mapperList = venusOaApprovalRecordDao.getVenusOaApprovalRecordListPage(appRescord);//0.请假 1.补卡
        CDO cdo1 = new CDO();
        for (CDO cdo : mapperList) {
            String card_time = cdo.getString("card_time");//
            Date parse = null;
            try {
                parse = sdf.parse(card_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (parse.before(date)&&!parse.equals(date)){//判断请假的结束时间是都小于当前时间
                cdo1.set("id",cdo.getLong("id"));
                cdo1.set("approval_state",2);
                cdo1.set("update_time",new Date());
                venusOaApprovalRecordDao.updateVenusOaApprovalRecordById(cdo1);

                //修改审批表信息
                CDO after = new CDO();//审批表
                after.set("pid",cdo.getLong("id"));
                after.set("approval_state",2);
                after.set("approval_time",new Date());
                after.set("approval_opinion","已超过补卡日期的月份,系统自动拒绝");
                after.set("not_approved","0");
                venusOaApprovalRecordDao.updateVenusOaLeaveApproval(after);
            }
        }
    }


    /**
     * @Author Zwl
     * @Description //TODO 若当前时间超过请假开始时间 自动拒绝
     * @Date 2022-12-15 16:56:10
     * @Param
     * @return
     */
    @Scheduled(cron = "0 */30 * * * ?")//三十分钟走一次
    public void autoRejectApproval(){
        List<CDO> mapperList = venusOaApprovalRecordDao.autoRejectApproval();
        CDO cdo1 = new CDO();
        for (CDO cdo : mapperList) {
            cdo1.set("id",cdo.getLong("id"));
            cdo1.set("approval_state",2);
            cdo1.set("update_time",new Date());
            venusOaApprovalRecordDao.updateVenusOaApprovalRecordById(cdo1);
            //修改审批表信息
            CDO after = new CDO();//审批表
            after.set("pid",cdo.getLong("id"));
            after.set("approval_state",2);
            after.set("approval_time",new Date());
            after.set("approval_opinion","当前时间已超过请假开始时间,系统自动拒绝");
            after.set("not_approved","0");
            venusOaApprovalRecordDao.updateVenusOaLeaveApproval(after);
        }
    }


    /**
     * @Author Zwl
     * @Description //TODO 修改app灰页列表中年循环 修改为当年时间
     * @Date 2022-12-23 10:50:20
     * @Param
     * @return
     */
    @Scheduled(cron="0 0 0 1 * ?")//每月执行一次
    public void cycleDiscolor(){
        CDO update = new CDO();
        List<CDO> list = venusOaDiscolorationDao.cycleDiscolor();
        for (CDO cdo : list) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(cdo.getDate("start_time"));//设置起时间
            calendar.add(Calendar.YEAR, 1);//
            update.set("start_time", calendar.getTime());

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(cdo.getDate("end_time"));//设置起时间
            calendar2.add(Calendar.YEAR, 1);//
            update.set("end_time", calendar2.getTime());

            update.set("id",cdo.getString("id"));
            venusOaDiscolorationDao.updateVenusOaDiscolorationById(update);
        }
    }
}
